package com.jkc.xh.fragments;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jkc.xh.R;
import com.jkc.xh.activities.WebActivity_;
import com.jkc.xh.adapters.LogoViewPageAdapter;
import com.jkc.xh.constants.Constant;
import com.jkc.xh.fragments.core.BaseFragment;
import com.jkc.xh.models.AdImageModel;
import com.jkc.xh.models.HomeImagesModel;
import com.jkc.xh.models.NoticeModel;
import com.jkc.xh.network.ApiClient;
import com.jkc.xh.network.RestCallBack;
import com.jkc.xh.network.models.NoticeResponse;
import com.jkc.xh.network.models.RestError;
import com.jkc.xh.utils.CacheTools;
import com.jkc.xh.utils.ImageLoader;
import com.jkc.xh.utils.SecurePreferences;
import com.jkc.xh.views.headview.HomePageView1_;
import com.jkc.xh.views.headview.HomePageView2_;
import com.jkc.xh.views.widget.AutoScrollViewPager;
import com.jkc.xh.views.widget.TextViewAd;
import com.jkc.xh.views.widget.ToastUtil;
import com.viewpagerindicator.CirclePageIndicator;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import retrofit.Call;

/**
 * Created by zhangbreeze on 15/11/21.
 */
@EFragment(R.layout.fragment_home)
public class HomeFragment extends BaseFragment implements TextViewAd.onClickLitener{
    @ViewById(R.id.mPager)
    AutoScrollViewPager mPager;
    @ViewById(R.id.mIndicator)
    CirclePageIndicator mIndicator;
    @ViewById
    ImageView ivAdBottom;
    @ViewById
    ViewPager vp_pager;
    @ViewById
    LinearLayout m_imagelinear;
    @ViewById(R.id.tv_notice)
    TextViewAd mTvNotice;
    private int index = 0;

    @AfterViews
    public void initData() {
        requestImages();
        List<NoticeModel> noticeList = CacheTools.noticeList;
        if(null == noticeList){
            requestNotices();
        }else{
            mTvNotice.setmTexts(noticeList);
            mTvNotice.setOnClickLitener(HomeFragment.this);
        }
        boolean isShowed = SecurePreferences.getInstance().getBoolean("preference_notice_popup_show", false);
        if(!isShowed){
            requestNoticePopup();
            SecurePreferences.getInstance().edit().putBoolean("preference_notice_popup_show", true).commit();
        }
        List<View> views = new ArrayList<View>();
        views.add(HomePageView1_.build(getActivity()));
        views.add(HomePageView2_.build(getActivity()));
        vp_pager.setAdapter(new CustomPageAdapter(views));
        vp_pager.addOnPageChangeListener(m_pageChange);
        viewAdd(m_imagelinear);
    }

    private class CustomPageAdapter extends PagerAdapter {
        private List<View> views;

        public CustomPageAdapter(List<View> views) {
            this.views = views;
        }

        @Override
        public int getCount() {
            return views.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        public Object instantiateItem(ViewGroup container, final int position) {
            container.addView(views.get(position));
            return views.get(position);
        }

    }

    private void viewAdd(LinearLayout mNumLayout) {
        mNumLayout.removeAllViews();
        Bitmap bitmap = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.fast_n);
        for (int i = 0; i < 2; i++) {
            Button bt = new Button(getActivity());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(bitmap.getWidth(), bitmap.getHeight());
            params.setMargins(5, 5, 5, 5);
            bt.setLayoutParams(params);
            bt.setBackgroundResource(R.drawable.fast_n);
            mNumLayout.addView(bt);
        }
        Button currentBt = (Button) mNumLayout.getChildAt(0);
        currentBt.setBackgroundResource(R.drawable.fast_s);

    }

    private ViewPager.OnPageChangeListener m_pageChange = new ViewPager.OnPageChangeListener() {
        public void onPageScrollStateChanged(int arg0) {
        }

        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        public void onPageSelected(int arg0) {
            index = arg0;
            for (int i = 0; i < m_imagelinear.getChildCount(); i++) {
                if (i == arg0) {
                    Button currentBt = (Button) m_imagelinear.getChildAt(arg0);
                    currentBt.setBackgroundResource(R.drawable.fast_s);
                } else {
                    Button currentBt = (Button) m_imagelinear.getChildAt(i);
                    currentBt.setBackgroundResource(R.drawable.fast_n);
                }
            }
        }
    };

    private void requestImages() {
        Call imageCall = ApiClient.getApiService().homeImages();
        addJob(imageCall);
        imageCall.enqueue(new RestCallBack<HomeImagesModel>() {
            @Override
            public void success(HomeImagesModel model) {
                setTopImage(model.top);
                setBottomImage(model.bottom);
                setWelcomeImage(model.welcome);
            }

            @Override
            public void failure(RestError error) {
                ToastUtil.showToastShort(error.msg);
            }
        });
    }

    private void requestNotices(){
        Call noticeCall = ApiClient.getApiService().queryNoticeList();
        addJob(noticeCall);
        noticeCall.enqueue(new RestCallBack<NoticeResponse>() {
            @Override
            public void success(NoticeResponse response) {
                List<NoticeModel> noticeList = response.list;
                if(null != noticeList){
                    mTvNotice.setmTexts(noticeList);
                    mTvNotice.setOnClickLitener(HomeFragment.this);
                    mTvNotice.invalidate();
                }
            }

            @Override
            public void failure(RestError error) {
                ToastUtil.showToastShort(error.msg);
            }
        });
    }

    private void requestNoticePopup(){
        Call noticeCall = ApiClient.getApiService().queryNoticePopup();
        addJob(noticeCall);
        noticeCall.enqueue(new RestCallBack<NoticeResponse>() {
            @Override
            public void success(NoticeResponse response) {
                List<NoticeModel> noticeList = response.list;
                if(null != noticeList && noticeList.size() > 0){
                    List<Dialog> dialogList = new ArrayList<>();
                    for(NoticeModel notice : noticeList){
                        Dialog popupDialog = new Dialog(getContext(), R.style.Theme_AppCompat_Dialog_Alert);
                        popupDialog.setContentView(R.layout.dialog_notice_popup);
                        popupDialog.setCanceledOnTouchOutside(false);
                        TextView dlg_title= popupDialog.findViewById(R.id.title);
                        TextView dlg_content = popupDialog.findViewById(R.id.content);
                        ImageView close_btn = popupDialog.findViewById(R.id.close_btn);
                        ImageView confirm_btn = popupDialog.findViewById(R.id.confirm_btn);
                        dlg_title.setText(Html.fromHtml(notice.title));
                        dlg_content.setText(Html.fromHtml(notice.content));
                        dlg_content.setMovementMethod(ScrollingMovementMethod.getInstance());
                        close_btn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                popupDialog.cancel();
                            }
                        });
                        confirm_btn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                popupDialog.cancel();
                            }
                        });
                        dialogList.add(popupDialog);
                    }
                    int i = 0;
                    for(Dialog dialog : dialogList){
                        if(i == 0){
                            dialog.show();
                        }
                        ImageView close_btn = dialog.findViewById(R.id.close_btn);
                        ImageView confirm_btn = dialog.findViewById(R.id.confirm_btn);
                        final int index = i;
                        close_btn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.cancel();
                                if(index < dialogList.size() - 1){
                                    dialogList.get(index+1).show();
                                }
                            }
                        });
                        confirm_btn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.cancel();
                                if(index < dialogList.size() - 1){
                                    dialogList.get(index+1).show();
                                }
                            }
                        });
                        i++;
                    }
                }
            }

            @Override
            public void failure(RestError error) {
                ToastUtil.showToastShort(error.msg);
            }
        });
    }

    @Override
    public void onClick(String id) {
        Intent intent = new Intent(getActivity(), WebActivity_.class);
        intent.putExtra(Constant.ACTION_AD_URL, CacheTools.getPageUrl()+"/Index/Nest/article_view/id/"+id+"/m/1.html");
        startActivity(intent);
    }

    private void setTopImage(ArrayList<AdImageModel> images) {
        LogoViewPageAdapter mTopImageAdapter = new LogoViewPageAdapter();
        mTopImageAdapter.setData(images);
        mPager.setAdapter(mTopImageAdapter);
        mIndicator.setViewPager(mPager);

    }

    private void setBottomImage(ArrayList<AdImageModel> images) {
        if (images == null || images.size() == 0) {
            return;
        }
        final AdImageModel image = images.get(0);
        if (image == null || TextUtils.isEmpty(image.img)) {
            return;
        }
        ImageLoader.loadImage(image.img, ivAdBottom);
        if (TextUtils.isEmpty(image.link)) {
            return;
        }
        ivAdBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), WebActivity_.class);
                intent.putExtra(Constant.ACTION_AD_URL, image.link);
                startActivity(intent);
            }
        });
    }

    private void setWelcomeImage(ArrayList<AdImageModel> images) {

        if (images == null || images.size() == 0) {
            return;
        }
        AdImageModel image = images.get(0);
        if (image == null || TextUtils.isEmpty(image.img)) {
            return;
        }

        String lastImgUrl = SecurePreferences.getInstance().getString(Constant.PREFERENCE_WELCOME_PIC_URL, "");
        if (TextUtils.isEmpty(lastImgUrl) || !lastImgUrl.equals(image.img)) {
            ImageLoader.loadImageToDisk(getContext(), image.img, getContext().getFilesDir().getPath(), UUID.randomUUID().toString() + ".jpg", new ImageLoader.DownloadCompleteCallback() {
                @Override
                public void onComplete(String path) {
                    SecurePreferences.getInstance().edit().putString(Constant.PREFERENCE_WELCOME_PIC_PATH, path).commit();
                }
            });
        }
        if (!TextUtils.isEmpty(image.link)) {
            SecurePreferences.getInstance().edit().putString(Constant.PREFERENCE_WELCOME_LINK, image.link)
                    .putString(Constant.PREFERENCE_WELCOME_PIC_URL, image.img).commit();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        mPager.startAutoScroll();
    }

    @Override
    public void onPause() {
        super.onPause();
        mPager.stopAutoScroll();
    }

    @Click(R.id.function_buy)
    void openTradeBuy() {
        TradeBuyFragment_.builder().build().startFragment(getActivity());
    }


    @Click(R.id.function_weituo)
    void openDodayWeituo() {
        TodayWeituoFragment_.builder().build().startFragment(getActivity());
    }

    @Click(R.id.function_cancel)
    void openRevokeOrder() {
        RevokeOrderFragment_.builder().build().startFragment(getActivity());
    }

    @Click(R.id.function_more)
    void openMoreFunction() {
        MoreFunctionFragment_.builder().build().startFragment(getActivity());
    }

    @Click(R.id.function_sold)
    void openOrderSoldPart() {
        TradeSoldPartFragment_.builder().build().startFragment(getActivity());
    }

    @Click(R.id.function_sold_all)
    void openOrderSoldAll() {
        TradeSoldAllFragment_.builder().build().startFragment(getActivity());
    }

    @Click(R.id.function_my_factory)
    void openMyFactory() {
        MyFactoryFragment_.builder().build().startFragment(getActivity());
    }

    @Click(R.id.function_money_bill)
    void openMoneyBill() {
        MoneyBillFragment_.builder().build().startFragment(getActivity());
    }
}
